package com.dymall.user.controller;

import com.dymall.common.exception.UnauthorizedException;
import com.dymall.common.util.UserContext;
import com.dymall.user.domain.dto.req.RegisterReq;
import com.dymall.user.domain.dto.req.UserInfoResp;
import com.dymall.user.domain.dto.resp.RegisterResp;
import com.dymall.user.domain.dto.req.LoginReq;
import com.dymall.user.domain.dto.resp.LoginResp;
import com.dymall.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    /**
     * 登录
     * @param loginReq
     * @return LoginResp
     */
    @PostMapping("/login")
    public LoginResp login(@RequestBody @Validated LoginReq loginReq){
        return userService.login(loginReq);
    }

    /**
     * 扣减余额
     * @param pw    密码
     * @param amount    价格
     */
    @PutMapping("/money/deduct")
    public void deductMoney(@RequestParam("pw") String pw,@RequestParam("amount") Integer amount){
        userService.deductMoney(pw, amount);
    }

    /**
     * 注册
     * @param registerReq
     * @return RegisterResp
     */
    @PostMapping("/register")
    public RegisterResp register(@RequestBody RegisterReq registerReq) {
        return userService.register(registerReq);
    }

    /**
     * 查询余额
     * @param id
     * @return balance
     */
    @GetMapping({"/balance/{id}", "/balance"})
    public Integer getBalance(@PathVariable(value = "id", required = false) Long id){
        // 可传入id也可可获取当前用户id
        Long userId = (id != null) ? id : UserContext.getUser();
        if (userId == null) {
            throw new RuntimeException("用户id错误");
        }
        return userService.getBalanceByUserId(userId);
    }

    /**
     * 获取用户信息
     * @return UserInfoResp
     */
    @GetMapping("/info")
    public UserInfoResp getUserInfo() {
        Long userId = UserContext.getUser();
        if (userId == null) {
            throw new UnauthorizedException("用户未登录");
        }
        return userService.getUserInfo(userId);
    }
}

